package com.kx.smartdevice.service.impl;

import com.kx.smartdevice.constants.ResultCode;
import com.kx.smartdevice.exceptions.AddErrorException;
import com.kx.smartdevice.mapper.HumitureMapper;
import com.kx.smartdevice.pojo.Humiture;
import com.kx.smartdevice.service.HumitureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName HumitureServiceImpl
 * @Author Sun
 * @Date 2021/6/2 19:18
 */
@Service
public class HumitureServiceImpl implements HumitureService {
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private HumitureMapper humitureMapper;

    @Override
    public void addHumiture(Humiture humiture) {

        if (humiture.isEmpty()) {
            throw new AddErrorException("数据为空", ResultCode.NULL_DATA);
        }
        humiture.setTemperature((humiture.getTemperature()-32)/1.8);//从华氏改成摄氏
        humitureMapper.addHumiture(humiture);
    }

    @Override
    public List<Humiture> getHumituresByParamMap(Map map) {
        Instant now = Instant.now();
        Object startdate = map.get("startdate");
        Object endstate = map.get("endstate");
        if (startdate == null||"".equals(startdate.toString().trim())) {
            map.put("startdate", dateFormat.format(Date.from(now.plusSeconds(-600))));//设置起点为当前时间之前1小时
        }
        if (endstate == null || "".equals(endstate.toString().trim())) {
            map.put("endstate",dateFormat.format( Date.from(now)));
        }
        if (map.get("deviceId")!=null&&-100==(Long)map.get("deviceId")) {
            map.remove("deviceId");
        }
        return humitureMapper.getHumituresByParamMap(map);
    }

    @EventListener
    public void onEvent(Humiture humiture) {
        addHumiture(humiture);
    }
}
